"""工具函数"""
from passlib.context import CryptContext


class Hashing(object):
    def __init__(self, schemes: str='bcrypt'):
        self.crypt = CryptContext(schemes=[schemes], deprecated="auto")

    def hash(self, raw_pwd: str) -> str:
        """
        密码加密
        :param raw_pwd: 原始密码
        :return: 密码的哈希值
        """
        return self.crypt.hash(raw_pwd)

    def verify(self, raw_pwd: str, hashed_pwd: str) -> bool:
        """
        验证密码是否正确
        :param raw_pwd: 原始密码
        :param hashed_pwd: 密码的哈希值
        :return:
        """
        return self.crypt.verify(raw_pwd, hashed_pwd)


if __name__ == '__main__':
    hashing = Hashing()
    hashed_pwd = hashing.hash("123456")
    print(hashed_pwd) # 加密后要保存到数据库中的哈希串
    # 把原密码和加密后的哈希串进行配对，验证通过则返回结果为True
    ret = hashing.verify("123456", hashed_pwd)
    print(ret)
